<?
require_once("ericdingle/php/AuthViewController.php");
require_once("ericdingle/model/post/PostProvider.php");
require_once("ericdingle/model/label/LabelProvider.php");

class EditPost extends AuthViewController {
	public function doGet($post = NULL) {
		// load the post
		if (!$post) {
			$postID = $_GET["postID"];
			if ($postID) {
				$postProvider = PostProvider::getInstance();
				$post = $postProvider->readByPostID($postID);
			} else {
				$post = new PostEntity();
			}
		}
		
		// load the labels
		$labelProvider = LabelProvider::getInstance();
		$labels = $labelProvider->read();

		// load the views
		require_once("ericdingle/php/Tabs.php");
		$this->loadView("ericdingle/view/header.php", array(
			"isLoggedIn" => true,
			"tabID" => TabID::EDIT_POST,
			"tabs" => $tabs,
			"css_files" => array("css/post.css", "css/editPost.css"),
			"js_files" => array("js/editPost.js")
		));
		$this->loadView("ericdingle/view/editPost.php", array(
			"post" => $post,
			"labels" => $labels
		));
		$this->loadView("ericdingle/view/footer.php");
	}
	
	public function doPost() {
		$labelIDs = ($_POST["labelIDs"] ? $_POST["labelIDs"] : array());
	
		// create a post entity to save or to preview
		$post = new PostEntity(
			$_POST["postID"],
			stripslashes($_POST["title"]),
			PostDate::fromMySQLStr($_POST["date"]),
			stripslashes($_POST["content"]),
			$labelIDs
		);
		
		if ($_POST["save"]) {
			$postProvider = PostProvider::getInstance();
			if ($post->getPostID()) {
				$postProvider->update($post);
			} else {
				$postProvider->create($post);
			}
			
			Header("Location: viewPosts");
			exit();
		}
		
		$this->doGet($post);
	}
}
?>
